package com.work.formaldehyde.orderfragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wang.avi.AVLoadingIndicatorView;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activity.DingDanXiangQingActivity;
import com.work.formaldehyde.activityadapter.DaiZhiFuAdapter;
import com.work.formaldehyde.model.AllDingDanModel;
import com.work.formaldehyde.model.WxModels;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.PayResult;
import com.work.formaldehyde.util.Url;
import com.work.formaldehyde.wxapi.WXPayEntryActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DZFFragment extends Fragment implements View.OnClickListener, DaiZhiFuAdapter.DetailViewHolderListener {
    //用于获取视图
    private View root;
    private ListView daizhifulist;
    private AVLoadingIndicatorView loding_avi;
    private IWXAPI api;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_daizhifu, container, false);//初始加载
        api = WXAPIFactory.createWXAPI(getActivity(), Url.WXAPPID);
        if (ApiUtils.isNetworkConnected(getActivity()))
            InitView(root);
        return root;
    }

    public static ArrayList<AllDingDanModel.data> new_list_views;
    public static DaiZhiFuAdapter myAdapters;

    public void Init() {
        new_list_views = new ArrayList<>();
        myAdapters = new DaiZhiFuAdapter(new_list_views,
                getActivity(), this);
        daizhifulist.setAdapter(myAdapters);
        okHttp_postFromParameters1();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(WXPayEntryActivity.wxpay_s){
            for (int del = 0; del < new_list_views.size(); del++) {
                if (new_list_views.get(del).getOrder_number().equals(Url.PAY_OREDNUM)) {
                    new_list_views.remove(del);
                }
            }
            myAdapters.notifyDataSetChanged();
            WXPayEntryActivity.wxpay_s=false;
            Url.PAY_OREDNUM="";
        }
    }

    /**
     * 初始加载视图
     */
    public void InitView(View view) {
        loding_avi = view.findViewById(R.id.loding_avi);
        loding_avi.show();
        daizhifulist = view.findViewById(R.id.daizhifulist);
        Init();
        daizhifulist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent tokpxq = new Intent(getActivity(), DingDanXiangQingActivity.class);
                tokpxq.putExtra("position", position + "");
                tokpxq.putExtra("username", new_list_views.get(position).getUser_name());
                tokpxq.putExtra("userphone", new_list_views.get(position).getUser_phone());
                tokpxq.putExtra("address", new_list_views.get(position).getUser_address());
                tokpxq.putExtra("ispay", new_list_views.get(position).getIspay());
                tokpxq.putExtra("type", "1");
                if (new_list_views.get(position).getGoods().size() > 1)
                    tokpxq.putExtra("duoge", "true");
                else
                    tokpxq.putExtra("duoge", "false");
                tokpxq.putExtra("shangpingimg", new_list_views.get(position).getGoods().get(0).getGoods_img());
                tokpxq.putExtra("shangpingname", new_list_views.get(position).getGoods().get(0).getGoods_name());
                tokpxq.putExtra("shangpingnum", new_list_views.get(position).getGoods().get(0).getGoods_num());
                tokpxq.putExtra("shangpingzongjia", new_list_views.get(position).getGoods().get(0).getGoods_discount_price());
                tokpxq.putExtra("dingdannum", new_list_views.get(position).getOrder_number());
                tokpxq.putExtra("xiadanshijian", new_list_views.get(position).getCreate_time());
                tokpxq.putExtra("zhifufangshi", new_list_views.get(position).getPay_type());
                tokpxq.putExtra("zhifushijian", new_list_views.get(position).getPay_time());
                tokpxq.putExtra("tuihuo", new_list_views.get(position).getOrder_status());
                startActivity(tokpxq, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        }
    }

    private void okHttp_postFromParameters1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder()
//                            .add("uid", Url.USER_ID).add("status", "0").build();
//                    Request request = new Request.Builder().url(Url.GETDINGDANLIST).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.ADDDINGDANS+"?uid="+ Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN+"&status=0").build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public AllDingDanModel allDingDanModel;
    public Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    loding_avi.hide();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        allDingDanModel = gson.fromJson(msg.obj.toString(),
                                AllDingDanModel.class);
                        new_list_views.addAll(allDingDanModel.getData());
                        Collections.reverse(new_list_views);
                        myAdapters.notifyDataSetChanged();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    private String ordnum = "";

    @Override
    public void setData(DaiZhiFuAdapter.init viewHolder, final int position) {
        viewHolder.quxiaodingdan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ordnum = new_list_views.get(position).getOrder_number();
                windows(getActivity(), v);
            }
        });
        viewHolder.quzhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                windowss(getActivity(), v, position);
            }
        });
    }

    private void okHttp_Del() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder()
                            .add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("order_number", ordnum).build();
                    Request request = new Request.Builder().url(Url.DELDINGDAN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getdel.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler getdel = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        for (int del = 0; del < new_list_views.size(); del++) {
                            if (new_list_views.get(del).getOrder_number().equals(ordnum)) {
                                new_list_views.remove(del);
                            }
                        }
                        for(int dels = 0; dels < AllFragment.new_list_views.size(); dels++){
                            if (AllFragment.new_list_views.get(dels).getOrder_number().equals(ordnum)) {
                                AllFragment.new_list_views.remove(dels);
                            }
                        }
                        AllFragment.myAdapters.notifyDataSetChanged();
                        myAdapters.notifyDataSetChanged();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private static PopupWindow popupWindows;

    public void windows(Context context, View v) {
        View popupwindowviews = null;
        popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_isdel, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ApiUtils.windows(getActivity(), daizhifulist, "取消中...");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                okHttp_Del();
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().setAttributes(lp);
        popupWindows.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    private String alipay_str = "";
    private String time_now = "", sign = "", biz_content = "", notify_url = "";

    public void windowss(Context context, View view, final int postion) {
        View popupwindowviews = null;
        popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_zfbandwx, null);
        RelativeLayout zfb = popupwindowviews.findViewById(R.id.zfb);
        zfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                alipay_str = "app_id=" + Url.ALIAPP_ID + "&charset=UTF-8&sign_type=RSA2&version=1.0&timestamp=" + time_now + "&sign=" + sign + "&biz_content=" + biz_content + "&method=alipay.trade.app.pay&notify_url=" + notify_url;
                orderNum = new_list_views.get(postion).getOrder_number();
                getalipay();
                popupWindows.dismiss();
            }
        });
        RelativeLayout wx = popupwindowviews.findViewById(R.id.wx);
        wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderNum = new_list_views.get(postion).getOrder_number();
                getpay();
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().setAttributes(lp);
        popupWindows.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    public String orderNum = "";

    private void getalipay() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("ordernum", orderNum)
                            .build();
                    Url.PAY_OREDNUM = orderNum;
//                    Request request = new Request.Builder().url(Url.GETALIPALY).post(formBody).build();
                    Request request = new Request.Builder().url(Url.ALIPAY).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getalihots.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler getalihots = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        alipay_str = success_Object.getString("data");
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void getpay() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("ordernum", orderNum)
                            .build();
//                    Request request = new Request.Builder().url(Url.GETWXPALY).post(formBody).build();
                    Request request = new Request.Builder().url(Url.WXPAY).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethots.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    WxModels wxModel;
    public Handler gethots = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        wxModel = gson.fromJson(msg.obj.toString(),
                                WxModels.class);
                        String partnerId = wxModel.getData().getPrepay_id();
                        String nonceStr = wxModel.getData().getNoncestr();
                        String times = "";
                        try {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date date = new Date(System.currentTimeMillis());
                            times = ApiUtils.dateToStamp(simpleDateFormat.format(date));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        PayReq request = new PayReq();
                        request.appId = Url.WXAPPID;
                        request.partnerId = Url.WXSHNUM;
                        request.prepayId = partnerId;
                        request.packageValue = "Sign=WXPay";
                        request.nonceStr = nonceStr;
                        request.timeStamp = wxModel.getData().getTimestamp();
                        request.sign = wxModel.getData().getRequest_sign();
                        api.sendReq(request);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    Runnable payRunnable = new Runnable() {
        private static final int SDK_PAY_FLAG = 1;

        @Override
        public void run() {
            PayTask alipay = new PayTask(getActivity());
            Map<String, String> result = alipay.payV2(alipay_str, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(getActivity());
        String version = payTask.getVersion();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            if (TextUtils.equals(resultStatus, "9000")) {
                ApiUtils.SetToast(getActivity(), "支付成功");
//                getalipays();
            } else {
                ApiUtils.SetToast(getActivity(), "支付失败");
            }
//            try {
//                JSONObject success_Object = new JSONObject(msg.obj.toString());
//                String code = success_Object.getString("msg");
//                ApiUtils.SetLog("支付=" + code);
//                if (code.equals("Success")) {
//                    ApiUtils.SetLog("支付结果:成功");
//                    getalipays();
//                } else {
//                    ApiUtils.SetLog("支付失败");
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }

        }
    };

    private void getalipays() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    formBody = new FormBody.Builder().add("paytype", "支付宝支付").add("order_number", Url.PAY_OREDNUM)
                            .build();
                    Request request = new Request.Builder().url(Url.PAYCSECSS).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getalihotss.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler getalihotss = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        for (int del = 0; del < new_list_views.size(); del++) {
                            if (new_list_views.get(del).getOrder_number().equals(Url.PAY_OREDNUM)) {
                                new_list_views.remove(del);
                            }
                        }
                        for(int dels = 0; dels < AllFragment.new_list_views.size(); dels++){
                            if (AllFragment.new_list_views.get(dels).getOrder_number().equals(Url.PAY_OREDNUM)) {
                                AllFragment.new_list_views.remove(dels);
                            }
                        }
                        myAdapters.notifyDataSetChanged();
                        AllFragment.myAdapters.notifyDataSetChanged();
                        Url.PAY_OREDNUM="";
                        DSHFragment.okHttp_postFromParameters1();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}